/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
$(function () {
    var myselfInfo = {"level": 0, "uid":0};
    var maxMessageNum = 100;
    var isMobile= false;
    init();

    WEB_SOCKET_SWF_LOCATION = "/assets/home/js/WebSocketMain.swf";
    WEB_SOCKET_DEBUG = true;
    
    try {
        WebSocket.loadFlashPolicyFile("xmlsocket://" + host + ":10843");
    } catch (e) {
    }
    
    var ws = new WebSocket(wsAddress);
    ws.onopen = function () {
        userLogin();
    };
    ws.onmessage = function (event) {
        var data = event.data.split('\n');
        for (var i = 0; i < data.length; i++) {
            var messages = data[i];
//            console.log("receive msg:" + messages);

            var prefix = messages.substr(0, 4);
            var content = messages.substr(5);
//            console.log("prefix" + prefix + "  content:" + content);

            switch (prefix) {
                case "1001":
                    loginResult(content);
                    break;
                case "1005":
                    setGuestInfo(content);
                    break;
                case "1200":
                    showOnLineUsers(content);
                    break;
                case "1110":
                    showMessage(content);
                    break;
                case "1101":
                    snedMessageResult(content);
                    break;
                case "9001":
                    layer.msg("请登录后再发言。");
                default:
            }
        }
    };
    ws.onclose = function () {
        setTimeout(function () {
            layer.msg("无法连接到聊天室");
        }, 500);
    };

    ws.onerror = function () {
        reconnect();
    };

    function init() {
        timer();
        calHeight();    //自动调整消息框高度
        parseMyselfInfo();
        beautySelect();
        checkIsMobile();
        autuAdaptper();
    }
    
    
    
//    $(window).load(function() {
//        calHeight();
//    });

    // 当视频窗口改变或者窗口尺寸发生改变时，自动适配高度
    function autuAdaptper(){
        window.onresize = calHeight;
        var total = 0;
        if (isMobile){
            var interval = setInterval(function(){
                if (total>100){
                    clearInterval(interval);
                }
                calHeight();
                total++;
//                console.log("auto h:"+total);
            },100);
         }
    }
    
    function checkIsMobile(){
        if ($("body").attr("isMobile")){
            isMobile = true;
        }
    }

    function beautySelect(){
        $('select.select').select();
    }

    function parseMyselfInfo() {
        jsonStr = $("#userData").attr("userData");
        if (jsonStr.length > 0) {
            jsonStr = jsonStr.replace("1000|", "");
            myselfInfo = JSON.parse(jsonStr);
        }
    }

    function userLogin(){
        if ($("#userData").attr("userData") != "") {
            ws.send($("#userData").attr("userData"));
        }
        getTID();
    }

    function setGuestInfo(content) {
        $("#guestName").html(content);
    }

    function getTID(){
        new Fingerprint2().get(function(result, components){
           console.log("id:"+result);
           ws.send("1010|"+result);
           return result;
      });
    }

    // 定时关闭置顶消息
    function timer() {
        setInterval(function () {
            $(".message_advance .message_list_2").each(function () {
                var timestamp = Date.parse(new Date());
                timestamp = timestamp / 1000;
                if (Math.abs(timestamp - $(this).attr("time")) > autoCloseMessageAdvance) {
                    $(this).animate({"margin-left": "-800px"}, 1000, "linear", function () {
                        $(this).remove();
                        calHeight();
                    });
                }
            })
        }, 1000);
    }

    function loginResult(content) {
        var obj = JSON.parse(content)
        if (!obj.Result) {
            layer.msg("进入房间失败");
        }
    }

    function snedMessageResult(content) {
        var obj = JSON.parse(content)
        if (!obj.Result) {
            layer.msg(obj.Msg);
        }
    }

    function showOnLineUsers(content) {
        var obj = JSON.parse(content);
        if (typeof(obj.Data) != "undefined" && obj.Data.length >= 1 && obj.Total >= 1) {
            var userListStr = "";
            var adminListStr = "";
            for (i = 0; i < obj.Data.length; i++) {
                var level = obj.Data[i].Level;
                var userIcon = obj.Data[i].Uid <= 0 ? '/assets/home/images/identity/-1.png' : '/assets/home/images/identity/' + level + '.png';
                var tempStr = "";
                tempStr += '<li>';
                tempStr += '<span class="member_cell_0"><img src="' + userIcon + '"><p>' + obj.Data[i].Name + '</p></span>';
                if (level >= 10000) {
                    tempStr += '<span class="member_cell_2">咨询</span>';
                } else if (myselfInfo.level >= 10000) {
                    tempStr += '<div style="display: none;" class="onopn">';
                    tempStr += '<span data-uid=' + obj.Data[i].Uid + ' data-cid=' + obj.Data[i].ClientID + ' class="member_cell_2 notip">禁IP</span>';
                    var Status = obj.Data[i].Status;
                    if (Status != 0) {
                        tempStr += '<span data-uid=' + obj.Data[i].Uid + ' data-cid=' + obj.Data[i].ClientID + ' class="member_cell_2 frozen">冻结</span>';
                        if(Status==1){var Text = "禁言";var status  = "2"; var rry = 'member_cell_2';}
                        if(Status==2){var Text = "恢复";var status  = "1"; var rry = 'member_rry';}
                        tempStr += '<span data-uid=' + obj.Data[i].Uid + ' data-cid=' + obj.Data[i].ClientID + ' data-status='+status+' class="'+rry+' gag">'+Text+'</span>';
                    }
                    tempStr += '</div>';
                }
                tempStr += '</li>';
                if (obj.Data[i].Level >= 10000) {
                    adminListStr += tempStr;
                } else {
                    userListStr += tempStr;
                }
            }


            $(".onLineUsers").html(adminListStr + userListStr);

            $(".totalOnlienUsers").html(obj.Total);
            $(".totalOnline").html(obj.Total);
            updateSelect(obj);
        }
    }

    // 更新下拉框的用户数据（对某人说）
    function updateSelect(obj){
        var selectUserFrom = $("#userfrom");
        var selectUserTo = $("#userto");
        var UserFromVal = selectUserFrom.val();
        var UserToVal = selectUserTo.val();

        myselfInfo.level<10000 ? selectUserFrom.remove() : '';
        selectUserFrom.empty();
        selectUserTo.empty();
        var Myself = "<option value='0'>我</option>";
        var AllPeople = "<option value='0'>所有人</option>";
        selectUserFrom.append(Myself);
        selectUserTo.append(AllPeople);

        for (i = 0; i < obj.Data.length; i++) {
            var value = obj.Data[i].ClientID;
            var name = obj.Data[i].Name;
            if (myselfInfo.level>=10000){
                if (obj.Data[i].IP==-1){
                    selectUserFrom.append("<option value='"+value+"'>"+name+"</option>")
                }
                if (obj.Data[i].IP== "" && obj.Data[i].Level<10000){
                    selectUserTo.append("<option value='"+value+"'>"+name+"</option>")
                }
            }else{
                if (obj.Data[i].Level>=10000){
                    selectUserTo.append("<option value='"+value+"'>"+name+"</option>")
                }
            }
        }
        //恢复选中状态
         selectUserFrom.val(UserFromVal);
         selectUserTo.val(UserToVal);

    }

    $(document).on("mouseover mouseout", ".onLineUsers li", function (event) {
        if (event.type == "mouseover") {
            $(this).find(".onopn").show();
        } else if (event.type == "mouseout") {
            $(this).find(".onopn").hide();
        }
    });
    $(document).on("click", ".gag", function () {
        var cid = $(this).data('cid');
        var uid = $(this).data('uid');
        var status = $(this).data('status');
        var stext = $(this).text();
        $.ajax({
            type: 'get',
            url: '/ban',
            data: {cid: cid, uid: uid, status: status},
            success: function (data) {
                if (data.status) {
                    layer.msg(stext + '成功！');
                } else {
                    layer.msg(data.msg);
                }
            }
        })
    });
    $(document).on("click", ".frozen", function () {
        var cid = $(this).data('cid');
        var uid = $(this).data('uid');
        var status = 3;
        $.ajax({
            type: 'get',
            url: '/ban',
            data: {cid: cid, uid: uid, status: status},
            success: function (data) {
                if (data.status) {
                    layer.msg('冻结成功！');
                } else {
                    layer.msg(data.msg);
                }
            }
        })
    });
    $(document).on("click", ".notip", function () {
        var cid = $(this).data('cid');
        var uid = $(this).data('uid');
        var Ip = 'ip';
        $.ajax({
            type: 'get',
            url: '/ban',
            data: {ipcid: cid, ipuid: uid},
            success: function (data) {
                if (data.status) {
                    layer.msg(data.msg);
                } else {
                    layer.msg(data.msg);
                }
            }
        })
    });

    function showMessage(content) {
        var content = content.split('\n');
        var msgStr = "";
        var megStrAdvance = "";
        for (var i = 0; i < content.length; i++) {
            obj = JSON.parse(content[i]);
            var timestamp = Date.parse(new Date());
            timestamp = timestamp / 1000;

            if (obj.MessageType ==0 && obj.UserFrom.Level >= 10000 && Math.abs(timestamp - obj.Time) <= autoCloseMessageAdvance) {
                megStrAdvance = htmlTemplateTopMsg(obj);
                $(".message_advance").append(megStrAdvance);
                calHeight();
            }

            msgStr = htmlTemplateMsg(obj)
            appendChatMsg(msgStr);
        }

        //弹幕配置
        processBarrager(obj);

        //parse face
        $(".chatInfo").parseEmotion();
        $(".message_list_2").parseEmotion();

        // 表情解析后，若有大图片，需要重新滚动
        scrollBottom();
    }

    // 管理员置顶消息模板
    function htmlTemplateTopMsg(obj){
        var megStrAdvance = "";
        var timestamp = Date.parse(new Date()) / 1000;
        megStrAdvance += '<div class="message_list_2" time=' + timestamp + '>';
        megStrAdvance += '    <div class="message_cell_5">';
        megStrAdvance += '       <dl><dt>' + obj.UserFrom.Name + '</dt><dd>' + formatDateTime(obj.Time) + '</dd></dl>';
        megStrAdvance += '    </div>';
        megStrAdvance += '    <div class="message_cell_6">' + obj.Data + '</div>';
        megStrAdvance += '</div>';
        return megStrAdvance;
    }

    // 普通消息模板
    function htmlTemplateMsg(obj){
        var msgStr = "";

        // 公聊
        if (obj.MessageType == 0){
            var userIcon = obj.UserFrom.Uid <= 0 ? '/assets/home/images/identity/-1.png' : '/assets/home/images/identity/' + obj.UserFrom.Level + '.png';
            msgStr += '<div class="message_list_1 ">';
            msgStr += '<div class="message_cell_1">';
            msgStr += '<ul>';
            msgStr += '<li><p>' + formatDateTime(obj.Time) + '</p></li>';
            msgStr += '<li><b><img src="' + userIcon + '"/></b></li>';
            msgStr += '</ul>';
            msgStr += '<div class="message_table_1">';
            msgStr += '<table>';
            msgStr += '<tr>';
            msgStr += '<td><strong>' + obj.UserFrom.Name + '</strong></td>';
            msgStr += '<td><div class="message_txt_1"><span>' + obj.Data + '</span></div></td>';
            msgStr += '</tr>';
            msgStr += '</table>';
            msgStr += '</div>';
            msgStr += '</div>';

            // 如果是管理员，增加禁言等控制按钮
            if (myselfInfo.level >= 10000 && obj.UserFrom.Level < 10000) {
                msgStr += '<div style="display: none;float: left" class="onopn">';
                msgStr += '<span data-uid=' + obj.UserFrom.Uid + ' data-cid=' + obj.UserFrom.ClientID + ' class="member_cell_2 notip">禁IP</span>';
                var Status = obj.UserFrom.Status;
                if (Status != 0) {
                    msgStr += '<span data-uid=' + obj.UserFrom.Uid + ' data-cid=' + obj.UserFrom.ClientID + ' class="member_cell_2 frozen">冻结</span>';
                    if(Status==1){
                        var Text = "禁言";
                        var status  = "2";
                        msgStr += '<span data-uid=' + obj.UserFrom.Uid + ' data-cid=' + obj.UserFrom.ClientID + ' data-status='+status+' class="member_cell_2 gag">'+Text+'</span>';
                    }
                }
                msgStr += '<span data-uid=' + obj.UserFrom.Uid + ' data-cid=' + obj.UserFrom.ClientID + ' class="member_cell_2">私聊</span>';
                msgStr += '</div>';
            }
            msgStr += '</div>';
        }else if(obj.MessageType == 1){ // 1V1私聊
            var sender = "";
            var receiver = "";
            if (obj.UserFrom.Uid == myselfInfo.uid){
                sender = "我";
                receiver = obj.UserTo.Name;
            }else{
                sender = obj.UserFrom.Name;
                receiver = "我";
            }
            msgStr += '<div class="message_list_1">';
            msgStr += '<div class="message_cell_1">';
            msgStr += '<ul>';
            msgStr += '<li><p>' + formatDateTime(obj.Time) + '</p></li>';
            msgStr += '<li><h3>'+sender+'</h3><span>对</span></li>';
            msgStr += '</ul>';
            msgStr += '<div class="message_table_1">';
            msgStr += '<table>';
            msgStr += '<tr>';
            msgStr += '<td><div class="message_tr_1"><h3>'+receiver+'</h3><span>说：</span></div></td>';
            msgStr += '<td><div class="message_txt_1"><span>'+obj.Data+'</span></div></td>';
            msgStr += '</tr>';
            msgStr += '</table>';
            msgStr += '</div>';
            msgStr += '</div>';
            msgStr += '</div>';
        }

        return msgStr;

    }

    // 那些用户需要显示弹幕
    function processBarrager(obj){
        // timeout
        var timestamp = Date.parse(new Date())/ 1000;
        if (Math.abs(timestamp - obj.Time) > 180){
            return;
        }

        var barragerSystemOpen = $('#barrage_system').val(); //系统是否开启弹幕
        var defaultShowing =  $('#barrage_default').val(); // 开启后所有用户是否默认显示弹幕
        var onlyRootShowing = $('#barrage_admin').val(); //只有管理员才能使用弹幕
        var barrageUserSetting = $('#barrage_default').val(); // 用户自己是否打开或者关闭了弹幕

        var myselfOpened = defaultShowing || barrageUserSetting;

        if (!barragerSystemOpen){
            return;
        }

        if (onlyRootShowing && obj.UserFrom.Level < 10000){
            return;
        }

        if (myselfOpened){
            showBarrager(obj);
        }

    }


    // 显示弹幕
    function showBarrager(obj){

        var Data = obj.Data;
        var objTemp = $("<div></div>");
        objTemp.html(Data);
        objTemp.parseEmotion();
        Data = objTemp.append();
        var timeout =  Math.floor(Math.random()*1000);
        var timeDelayByLevel =  obj.UserFrom.Level * 2;
        timeDelayByLevel = timeDelayByLevel > 30 ? 30 : timeDelayByLevel;
        setTimeout(function(){
            var item = {
                info: Data, //文字
                href: 'javascript:;', //链接
                close: false, //显示关闭按钮
                speed: parseInt(20 + timeDelayByLevel + Math.floor(Math.random() * 10)), //延迟,单位秒,默认6
//                speed: 20, //延迟,单位秒,默认6
                color: '#fff', //颜色,默认白色
                old_ie_color: '#000000', //ie低版兼容色,不能与网页背景相同,默认黑色
                bg_color:'', //背景颜色
                opacity:0.9,//背景颜色透明度
            };

            // root level
            if (obj.UserFrom.Level >= 10000) {
                item.img = '/assets/home/barrager/static/img/heisenberg.png';
//                item.img = '/assets/home/images/identity/10000.png';
                item.bg_color = '#dd1234';
                item.speed = 50;
            }
            $('body').barrager(item);
        }, timeout);
    }

    $(document).on("mouseover mouseout", ".message_list_1", function (event) {
        if (event.type == "mouseover") {
            $(this).find(".onopn").show();
        } else if (event.type == "mouseout") {
            $(this).find(".onopn").hide();
        }
    });
    
    function calHeight() {
        calHeightPC();
        calHeightMobile();
    }
    
    function calHeightPC(){
        if (!isMobile){
            var total = document.documentElement.clientHeight;
            var messageBoxHeight = total - $(".message_advance").height() - 220 - $(".message_telCell_1").height();
            $(".chatInfo").css("height", messageBoxHeight);
        }
    }
    
    function calHeightMobile() {
        if (isMobile){
            var total = document.documentElement.clientHeight;
            var playerHeight = $(".player_box").height();
            var headerHeight = $(".header_wrap").height();
            var mobileMessageBoxHeight = total - playerHeight - headerHeight - 69;
            $(".chatInfo").css("height", mobileMessageBoxHeight);
        }
    }

    function appendChatMsg(item) {
        $(".chatInfo").append(item);
        if ($(".chatInfo .message_list_1").length > maxMessageNum) {
            $(".chatInfo .message_list_1:first").remove();
        }
        scrollBottom();
    }
    
    function scrollBottom(){
        $(".chatInfo").scrollTop($(".chatInfo").scrollTop() + 3000);
    }
    
    $("#btnCommit").bind("click", function () {
        commit();
    });

    function commit() {
        if (!ws) {
            layer.msg("已经断开连接");
            return false;
        }
        if (!$(".msg").val()) {
            layer.msg("聊天内容不能为空");
            return false;
        }
        var CidFrom = parseInt($("#userfrom").val());
        var CidTo = parseInt($("#userto").val());
//        console.log("CidFrom:"+CidFrom+"  CidTo:"+CidTo);
        sendMessage($(".msg").val(), CidFrom, CidTo);
        $(".msg").val("");
        return false;
    }

    function sendMessage(msgStr, CidFrom, CidTo) {
        if (!ws) {
            layer.msg("已经断开连接");
            return false;
        }
        var prefix = "1100|";
        var msg = {Data: msgStr, ClientIDFrom: CidFrom, ClientIDTo:CidTo};
        ws.send(prefix + JSON.stringify(msg));
    }

    function formatDateTime(/** timestamp=0 **/) {
        var ts = arguments[0] || 0;
        var t, y, m, d, h, i, s;
        t = ts ? new Date(ts * 1000) : new Date();
        y = t.getFullYear();
        m = t.getMonth() + 1;
        d = t.getDate();
        h = t.getHours();
        i = t.getMinutes();
        s = t.getSeconds();
        // 可根据需要在这里定义时间格式
//	    return y+'-'+(m<10?'0'+m:m)+'-'+(d<10?'0'+d:d)+' '+(h<10?'0'+h:h)+':'+(i<10?'0'+i:i)+':'+(s<10?'0'+s:s);  
        return (h < 10 ? '0' + h : h) + ':' + (i < 10 ? '0' + i : i);
    }
    
    $(".clearMessage").bind("click", function(){
        $('.chatInfo').html("");
    });

});

function toDesktop(sUrl, sName) {
    try {
        var WshShell = new ActiveXObject("WScript.Shell");
        var oUrlLink = WshShell.CreateShortcut(WshShell
                .SpecialFolders("Desktop")
            + "\\" + sName + ".url");
        oUrlLink.TargetPath = sUrl;
        oUrlLink.Save();
    } catch (e) {
        alert("当前IE安全级别不允许操作！");
    }
}
